<template>
  <div class="ai-solver">
    <div class="ai-solver-header">
      <h3>🤖 AI智能解题</h3>
      <div class="header-actions">
        <span v-if="conversationId" class="conversation-info">
          对话ID: {{ conversationId.substring(0, 8) }}...
        </span>
        <button 
          @click="toggleSolver" 
          class="toggle-btn"
          :class="{ active: isExpanded }"
        >
          {{ isExpanded ? '收起' : '展开' }}
        </button>
      </div>
    </div>
    
    <div v-if="isExpanded" class="ai-solver-content">
      <div class="question-input">
        <textarea
          v-model="question"
          placeholder="请输入您的问题..."
          rows="3"
          :disabled="isLoading"
        ></textarea>
        
        <!-- 图片上传区域 -->
        <div class="image-upload-area">
          <input 
            type="file" 
            ref="imageInput" 
            @change="handleImageUpload" 
            accept="image/*"
            :disabled="isLoading"
            style="display: none"
          />
          <div class="upload-zone" @click="triggerImageUpload" :class="{ disabled: isLoading }">
            <div v-if="!selectedImage" class="upload-placeholder">
              <el-icon><Camera /></el-icon>
              <span>点击上传图片或拖拽图片到此处</span>
            </div>
            <div v-else class="image-preview">
              <img :src="selectedImage" alt="上传的图片" />
              <button @click.stop="removeImage" class="remove-image-btn">×</button>
            </div>
          </div>
        </div>
        
        <div class="input-actions">
          <div class="action-left">
            <select v-model="questionType" :disabled="isLoading" class="type-select">
              <option value="">选择问题类型</option>
              <option value="数学">数学</option>
              <option value="物理">物理</option>
              <option value="化学">化学</option>
              <option value="生物">生物</option>
              <option value="编程">编程</option>
              <option value="图像识别">图像识别</option>
              <option value="其他">其他</option>
            </select>
            <button 
              v-if="result && result.success" 
              @click="clearResult" 
              class="clear-btn"
              title="清除结果"
            >
              <el-icon><Delete /></el-icon>
            </button>
          </div>
          <button 
            @click="solveQuestion" 
            :disabled="!question.trim() || isLoading"
            class="solve-btn"
          >
            <span v-if="isLoading" class="loading-spinner"></span>
            <el-icon v-if="!isLoading"><ChatDotRound /></el-icon>
            {{ isLoading ? 'AI思考中...' : '开始解题' }}
          </button>
        </div>
      </div>
      
      <div v-if="result" class="ai-result">
        <div class="result-header">
          <h4>AI解答</h4>
          <div class="result-actions">
            <span class="result-status" :class="{ success: result.success, error: !result.success }">
              {{ result.success ? '解答完成' : '解答失败' }}
            </span>
            <button v-if="result.success" @click="copyAnswer" class="copy-btn">
              <el-icon><CopyDocument /></el-icon>
              复制
            </button>
            <button v-if="result.success" @click="copyAnswer" class="share-btn">
              <el-icon><Share /></el-icon>
              分享
            </button>
          </div>
        </div>
        
        <div v-if="result" class="answer-content">
          <!-- 调试信息 -->
          <div style="background: #f0f0f0; padding: 10px; margin: 10px 0; font-size: 12px; border: 1px solid #ddd; border-radius: 4px;">
            <div><strong>调试信息：</strong></div>
            <div>displayedAnswer长度: {{ displayedAnswer.length }}</div>
            <div>displayedAnswer内容: "{{ displayedAnswer.substring(0, 100) }}{{ displayedAnswer.length > 100 ? '...' : '' }}"</div>
            <div>result.answer长度: {{ (result as any)?.answer?.length || 0 }}</div>
            <div>result.answer内容: "{{ ((result as any)?.answer || '').substring(0, 100) }}{{ ((result as any)?.answer || '').length > 100 ? '...' : '' }}"</div>
            <div>result.success: {{ result.success }}</div>
            <div>isLoading: {{ isLoading }}</div>
            <div>result存在: {{ !!result }}</div>
            <div>当前时间: {{ new Date().toLocaleTimeString() }}</div>
          </div>
          <div v-if="result.success" class="answer-text" v-html="formatAnswer(displayedAnswer || (result as any)?.answer || '')"></div>
          <div v-else class="error-content">
            <p class="error-message">{{ (result as any)?.error || 'AI解答失败' }}</p>
          </div>
          
          <div v-if="result.followUpQuestions && result.followUpQuestions.length > 0" class="follow-up">
            <h5>💡 相关问题建议：</h5>
            <div class="follow-up-questions">
              <button 
                v-for="(question, index) in result.followUpQuestions" 
                :key="index"
                @click="askFollowUp(question)"
                class="follow-up-btn"
              >
                {{ question }}
              </button>
            </div>
          </div>
        </div>
        
        <div v-else class="error-content">
          <p class="error-message">{{ (result as any)?.error || 'AI解答失败' }}</p>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Camera, CopyDocument, Delete, ChatDotRound, Share } from '@element-plus/icons-vue'
import { aiSolverApi, type AiSolverRequest, type AiSolverResponse } from '@/api/ai-solver'
import { useUserStore } from '@/store/user'
import { useAiSolverStore } from '@/store/ai-solver'

const userStore = useUserStore()
const aiSolverStore = useAiSolverStore()

const isExpanded = ref(false)
const question = ref('')
const questionType = ref('')
const isLoading = ref(false)
const result = ref<AiSolverResponse | null>(null)
const conversationId = ref('')
const selectedImage = ref('')
const imageFile = ref<File | null>(null)
const displayedAnswer = ref('')
const imageInput = ref<HTMLInputElement>()

// 打字机效果
// const typewriterSpeed = 30 // 毫秒
let typewriterTimer: ReturnType<typeof setTimeout> | null = null

const toggleSolver = () => {
  isExpanded.value = !isExpanded.value
  if (!isExpanded.value) {
    result.value = null
    displayedAnswer.value = ''
    clearTypewriter()
  }
}

const solveQuestion = async () => {
  if (!question.value.trim()) return
  
  console.log('开始AI解题，问题:', question.value)
  isLoading.value = true
  result.value = null
  displayedAnswer.value = ''
  clearTypewriter()
  
  try {
    if (imageFile.value) {
      // 如果有图片，使用流式图片解题API
      console.log('使用图片解题API')
      const formData = new FormData()
      formData.append('question', question.value)
      formData.append('questionType', questionType.value || '图像识别')
      formData.append('userId', (userStore.user?.id || 1).toString())
      formData.append('image', imageFile.value)
      
      await handleStreamResponse(aiSolverApi.solveQuestionWithImageStream(formData))
    } else {
      // 普通文本解题，使用流式API
      console.log('使用普通文本解题API')
      const request: AiSolverRequest = {
        question: question.value,
        questionType: questionType.value,
        userId: Number(userStore.user?.id) || 1
      }
      
      console.log('发送请求:', request)
      await handleStreamResponse(aiSolverApi.solveQuestionStream(request))
    }
  } catch (error) {
    console.error('AI解题失败:', error)
    result.value = {
      answer: '',
      followUpQuestions: [],
      conversationId: '',
      messageId: '',
      success: false,
      error: '网络错误，请稍后重试'
    }
  } finally {
    isLoading.value = false
    console.log('AI解题完成，最终结果:', result.value)
  }
}

const handleStreamResponse = async (streamPromise: Promise<ReadableStream<Uint8Array>>) => {
  try {
    console.log('=== 开始处理响应（直接接收方案） ===')
    const stream = await streamPromise
    console.log('响应流对象:', stream)
    
    if (!stream) {
      throw new Error('响应流对象为空')
    }
    
    const reader = stream.getReader()
    console.log('响应流读取器:', reader)
    
    const decoder = new TextDecoder()
    let fullAnswer = ''
    let conversationId = ''
    let messageId = ''
    let buffer = ''
    
    // 初始化结果对象
    result.value = {
      answer: '',
      followUpQuestions: [],
      conversationId: '',
      messageId: '',
      success: true,
      error: undefined
    }
    
    console.log('初始化结果对象:', result.value)
    console.log('开始读取响应数据...')
    
    let chunkCount = 0
    
    try {
      while (true) {
        console.log(`=== 准备读取第${chunkCount + 1}个数据块 ===`)
        const { done, value } = await reader.read()
        chunkCount++
        
        console.log(`=== 读取第${chunkCount}个数据块 ===`)
        console.log('done:', done)
        console.log('value:', value)
        
        if (done) {
          console.log('响应结束，总共读取了', chunkCount, '个数据块')
          break
        }
        
        if (!value) {
          console.log('数据块为空，跳过')
          continue
        }
        
        const chunk = decoder.decode(value, { stream: true })
        console.log('=== 原始数据块 ===')
        console.log('chunk length:', chunk.length)
        console.log('chunk content:', JSON.stringify(chunk))
        console.log('chunk preview:', chunk.substring(0, 200) + (chunk.length > 200 ? '...' : ''))
        
        // 将新数据添加到缓冲区
        buffer += chunk
        console.log('当前缓冲区内容:', JSON.stringify(buffer))
        
        // 按行分割数据
        const lines = buffer.split('\n')
        console.log('分割后的行数:', lines.length)
        
        // 保留最后一个不完整的行
        buffer = lines.pop() || ''
        console.log('保留的缓冲区:', JSON.stringify(buffer))
        
        for (let i = 0; i < lines.length; i++) {
          const line = lines[i]
          console.log(`--- 处理第${i+1}行 ---`)
          console.log('line content:', JSON.stringify(line))
          
          if (line.trim() === '') {
            console.log('跳过空行')
            continue
          }
          
          if (line.startsWith('data: ')) {
            const data = line.slice(6).trim()
            console.log('提取的data:', JSON.stringify(data))
            
            if (data === '[DONE]' || data === '') {
              console.log('跳过空数据或结束标记')
              continue
            }
            
            console.log('=== 处理消息数据 ===')
            console.log('原始data:', data)
            
            // 直接处理消息内容
            fullAnswer += data
            displayedAnswer.value = fullAnswer
            
            // 确保result对象也被更新
            if (result.value) {
              (result.value as any).answer = fullAnswer
            }
            
            console.log('=== AiSolver更新状态 ===')
            console.log('收到数据片段:', data)
            console.log('当前完整回答:', fullAnswer)
            console.log('displayedAnswer.value:', displayedAnswer.value)
            console.log('result.value.answer:', (result.value as any)?.answer)
            
            // 强制触发响应式更新
            await nextTick()
            
            console.log('=== 更新后的状态 ===')
            console.log('收到消息片段:', data)
            console.log('当前完整回答长度:', fullAnswer.length)
            console.log('当前完整回答内容:', fullAnswer)
            console.log('displayedAnswer.value长度:', displayedAnswer.value.length)
            console.log('displayedAnswer.value内容:', displayedAnswer.value)
            console.log('result.value.answer长度:', (result.value as any)?.answer?.length || 0)
            console.log('result.value.answer内容:', (result.value as any)?.answer || '')
            console.log('result.value存在:', !!result.value)
            console.log('result.value.success:', (result.value as any)?.success)
            
          } else if (line.startsWith('event: ')) {
            const eventType = line.slice(7).trim()
            console.log('=== 处理事件 ===')
            console.log('事件类型:', eventType)
            
            // 如果是完成事件，确保最终结果正确设置
            if (eventType === 'complete') {
              console.log('=== 收到完成事件 ===')
              console.log('最终回答长度:', fullAnswer.length)
              console.log('最终回答内容:', fullAnswer)
              
              if (result.value) {
                (result.value as any).answer = fullAnswer;
                (result.value as any).success = true;
                console.log('设置完成状态，result.value:', result.value)
              }
            }
          } else if (line.trim() !== '') {
            console.log('未识别的行:', line)
          }
        }
      }
      
      // 处理缓冲区中剩余的数据
      if (buffer.trim()) {
        console.log('处理缓冲区剩余数据:', JSON.stringify(buffer))
        const lines = buffer.split('\n')
        for (const line of lines) {
          if (line.trim() === '') continue
          
          if (line.startsWith('data: ')) {
            const data = line.slice(6).trim()
            if (data && data !== '[DONE]') {
              fullAnswer += data
              displayedAnswer.value = fullAnswer
              if (result.value) {
                (result.value as any).answer = fullAnswer
              }
              // 强制触发响应式更新
              await nextTick()
            }
          }
        }
      }
      
    } catch (readError: any) {
      console.error('读取响应数据时出错:', readError)
      throw readError
    } finally {
      reader.releaseLock()
    }
    
    console.log('=== 响应处理完成 ===')
    console.log('最终完整回答长度:', fullAnswer.length)
    console.log('最终完整回答内容:', fullAnswer)
    
    // 更新最终结果
    if (result.value) {
      (result.value as any).answer = fullAnswer;
      (result.value as any).conversationId = conversationId;
      (result.value as any).messageId = messageId;
      (result.value as any).success = true;
      console.log('最终结果对象:', result.value)
    }
    
    // 如果没有收到任何内容，设置一个默认消息
    if (!fullAnswer.trim()) {
      console.log('没有收到任何内容，设置默认消息')
      fullAnswer = 'AI正在思考中，请稍候...'
      if (result.value) {
        (result.value as any).answer = fullAnswer;
        (result.value as any).success = false;
        (result.value as any).error = '未收到AI回复，请重试';
      }
      displayedAnswer.value = fullAnswer
    }
    
    // 保存到对话历史
    if (result.value) {
      console.log('保存到对话历史')
      aiSolverStore.addConversation(
        question.value, 
        result.value, 
        questionType.value, 
        selectedImage.value
      )
    }
    
    console.log('=== 响应处理函数结束 ===')
    
  } catch (error: any) {
    console.error('=== 处理响应失败 ===')
    console.error('错误类型:', error?.constructor?.name || 'Unknown')
    console.error('错误消息:', error?.message || 'Unknown error')
    console.error('错误堆栈:', error?.stack || 'No stack trace')
    
    // 设置错误状态
    if (result.value) {
      (result.value as any).success = false;
      (result.value as any).error = error?.message || '处理响应失败';
    }
    
    throw error
  }
}

// const startTypewriter = (text: string) => {
//   clearTypewriter()
//   let index = 0
//   displayedAnswer.value = ''
  
//   const type = () => {
//     if (index < text.length) {
//       displayedAnswer.value += text[index]
//       index++
//       typewriterTimer = setTimeout(type, typewriterSpeed)
//     }
//   }
  
//   type()
// }

const clearTypewriter = () => {
  if (typewriterTimer) {
    clearTimeout(typewriterTimer)
    typewriterTimer = null
  }
}

const handleImageUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (file) {
    if (file.size > 10 * 1024 * 1024) { // 10MB限制
      ElMessage.error('图片大小不能超过10MB')
      return
    }
    
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return
    }
    
    imageFile.value = file
    const reader = new FileReader()
    reader.onload = (e) => {
      selectedImage.value = e.target?.result as string
    }
    reader.readAsDataURL(file)
    
    // 自动选择图像识别类型
    if (!questionType.value) {
      questionType.value = '图像识别'
    }
  }
}

const triggerImageUpload = () => {
  if (!isLoading.value) {
    imageInput.value?.click()
  }
}

const removeImage = () => {
  selectedImage.value = ''
  imageFile.value = null
  if (imageInput.value) {
    imageInput.value.value = ''
  }
}

const askFollowUp = (followUpQuestion: string) => {
  question.value = followUpQuestion
  solveQuestion()
}

const copyAnswer = async () => {
  if (result.value?.answer) {
    try {
      await navigator.clipboard.writeText(result.value.answer)
      ElMessage.success('答案已复制到剪贴板')
    } catch (error) {
      ElMessage.error('复制失败，请手动复制')
    }
  }
}

const clearResult = () => {
  result.value = null
  displayedAnswer.value = ''
  clearTypewriter()
  ElMessage.info('已清除AI解答结果')
}



// 格式化答案
const formatAnswer = (answer: string) => {
  if (!answer) return ''
  
  console.log('=== 格式化答案 ===')
  console.log('原始答案长度:', answer.length)
  console.log('原始答案内容:', answer)
  
  // 增强的格式化
  const formatted = answer
    .replace(/\n/g, '<br>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/🤖/g, '🤖')
    .replace(/💡/g, '💡')
    .replace(/📝/g, '📝')
    .replace(/🔍/g, '🔍')
    .replace(/✅/g, '✅')
  
  console.log('格式化后答案长度:', formatted.length)
  console.log('格式化后答案内容:', formatted)
  console.log('=== 格式化完成 ===')
  
  return formatted
}

onMounted(() => {
  // 加载本地对话历史
  aiSolverStore.loadFromLocalStorage()
  
  // 获取用户对话历史
  if (userStore.user?.id) {
    aiSolverStore.getUserConversationId(Number(userStore.user.id))
      .then((convId: string | null) => {
        conversationId.value = convId || ''
      })
      .catch(error => {
        console.error('获取对话历史失败:', error)
      })
  }
})
</script>

<style scoped>
.ai-solver {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  margin: 16px 0;
  overflow: hidden;
}

.ai-solver-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #fff;
  border-bottom: 1px solid #e9ecef;
}

.ai-solver-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.conversation-info {
  font-size: 12px;
  color: #666;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
}

.toggle-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.toggle-btn:hover {
  background: #0056b3;
}

.toggle-btn.active {
  background: #6c757d;
}

.ai-solver-content {
  padding: 16px;
}

.question-input textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
  font-size: 14px;
}

.question-input textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.image-upload-area {
  margin: 12px 0;
}

.upload-zone {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.upload-zone:hover:not(.disabled) {
  border-color: #007bff;
  background: #f0f8ff;
}

.upload-zone.disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #666;
}

.upload-placeholder .el-icon {
  font-size: 24px;
}

.image-preview {
  position: relative;
  display: inline-block;
}

.image-preview img {
  max-width: 200px;
  max-height: 150px;
  border-radius: 4px;
  object-fit: cover;
}

.remove-image-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #ff4757;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  gap: 12px;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.type-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  font-size: 14px;
}

.clear-btn {
  background: #ff4757;
  color: white;
  border: none;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.clear-btn:hover {
  background: #ff3742;
}

.solve-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.solve-btn:hover:not(:disabled) {
  background: #218838;
}

.solve-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.ai-result {
  margin-top: 20px;
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  overflow: hidden;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.result-header h4 {
  margin: 0;
  color: #333;
  font-size: 14px;
}

.result-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.result-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  font-weight: 500;
}

.result-status.success {
  background: #d4edda;
  color: #155724;
}

.result-status.error {
  background: #f8d7da;
  color: #721c24;
}

.copy-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: background-color 0.2s;
}

.copy-btn:hover {
  background: #5a6268;
}

.share-btn {
  background: #17a2b8;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: background-color 0.2s;
}

.share-btn:hover {
  background: #138496;
}

.answer-content {
  padding: 16px;
}

.answer-text {
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
}

.follow-up {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e9ecef;
}

.follow-up h5 {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 13px;
}

.follow-up-questions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.follow-up-btn {
  background: #e9ecef;
  color: #495057;
  border: 1px solid #dee2e6;
  padding: 6px 12px;
  border-radius: 16px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
  white-space: nowrap;
}

.follow-up-btn:hover {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.error-content {
  padding: 16px;
}

.error-message {
  color: #dc3545;
  margin: 0;
  font-size: 14px;
}
</style>
